package com.lagou.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.stereotype.Component;

/**
 * @author wuyuhan
 * @date 2021/1/10 15:24
 */
@Component(value = "MyZkClient")
public class MyZkClient {

    public String ip;
    public int port;
    private CuratorFramework zkClient;
    public static String path = "/lg-zkClient";


    public void initialize() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        //使用fluent编程风格
        zkClient = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(retryPolicy)
                .namespace("lg-zkClient")//独立的命名空间 /base 对于数据节点的任何操作，都是相对于/base,业务隔离
                .build();
        zkClient.start();
        System.out.println("会话创建完成。。");
//        zkClient = new ZkClient("127.0.0.1:2181", 5000);
        String node = String.format("/"+ip + ":" + port);

        String value = "0";
        String s = null;
        try {
            s = zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).
                    forPath(node, value.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("节点创建成功" + s);
    }

    public void updateTime(int second) {
        String node = String.format(ip + ":" + port);
        try {
            zkClient.setData().forPath(node, String.valueOf(second).getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
//        zkClient.writeData(path + "/" + ip + ":" + port, second);
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public static String getPath() {
        return path;
    }

    public static void setPath(String path) {
        com.lagou.zk.MyZkClient.path = path;
    }
}
